from odoo import models, api


class SbMESLocation(models.Model):
    _inherit = 'stock.location'

    def cron_all(self):
        records = self.env['stock.location'].sudo().search([])
        for rec in records:
            rec.location_upload_mes()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                rec.with_delay().location_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            self.with_delay().location_upload_mes()
        return res

    def location_upload_mes(self):
        """
        位置上传 MES 系统
        """
        location_list = []
        for record in self:
            location_list.append({
                "org_id": "0001",
                "store_code": record.warehouse_id.code,  # 仓库编码
                "storeloc_code": record.barcode,  # 储位编码
                "storeloc_type": 1,  # 储位类型 1:固定储位 2:移动储位 3:待检储位
                "storesub_code": "",  # 库区编码
                "storerack_code": "",  # 货架编码
                "is_valid": "Y",
                "remark": "0"  # 备注
            })
        data = {
            "docType": "BS_STORELOC",
            "updateType": "UPDATE",
            "data": location_list
        }
        self.env['s.mes.upload'].upload_data(data=data)
